//
//  RJPhotoImageView.m
//  Muses
//
//  Created by hzyd-wlj on 14/11/17.
//  Copyright (c) 2014年 yodo. All rights reserved.
//
#define KMaxZoomScale 2

#import "RJPhotoImageView.h"
#import "RJPhoto.h"
#import "SDWebImageDownloader.h"
#import "SDWebImageDownloaderOperation.h"
#import "Defines.h"
#import "UIView+Positioning.h"
@interface RJPhotoImageView()

@property(nonatomic,assign) CGFloat zoomStep;

@end
@implementation RJPhotoImageView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
        self.userInteractionEnabled = NO;
        //TODO
        UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
        scrollView.backgroundColor = [UIColor blackColor];
        scrollView.opaque = YES;
        [scrollView setBounces:NO];
        scrollView.alwaysBounceHorizontal = YES;
        scrollView.directionalLockEnabled = YES;
        [scrollView setMinimumZoomScale:1.0];
        [scrollView setMaximumZoomScale:KMaxZoomScale];
        scrollView.delegate = self;
        [self addSubview:scrollView];
        _scrollView = scrollView;
        self.zoomStep = KMaxZoomScale;
        
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(scrollView.frame), CGRectGetHeight(scrollView.frame))];
        imageView.backgroundColor = [UIColor clearColor];
        imageView.opaque = YES;
        imageView.contentMode = UIViewContentModeScaleAspectFit;
        [_scrollView addSubview:imageView];
        _imageView = imageView;
        
        UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
        activityView.frame = CGRectMake((CGRectGetWidth(self.frame) / 2) - 11.0f, CGRectGetHeight(self.frame) - 100.0f , 22.0f, 22.0f);
        activityView.center = CGPointMake(CGRectGetWidth(self.frame)/2, CGRectGetHeight(self.frame)/2);
        activityView.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin;
        [self addSubview:activityView];
        _activityView = activityView;
        
        
        UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTapHandle:)];
        [singleTap setNumberOfTapsRequired:1];
        [self.scrollView addGestureRecognizer:singleTap];
        
        UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleDouble:)];
        [doubleTap setNumberOfTapsRequired:2];
        [singleTap requireGestureRecognizerToFail:doubleTap];
        [self.scrollView addGestureRecognizer:doubleTap];
    
    }
    return self;
}

#pragma mark - Override
- (void)layoutSubviews{
    [super layoutSubviews];
    
    if (_scrollView.zoomScale == 1.0f) {
        //[self layoutScrollViewAnimated:YES];
    }
}

- (void)setPhoto:(RJPhoto *)photo
{
    if (!photo) return;
    if ([photo isEqual:self.photo]) return;
    
    if (self.photo != nil) {
        [_downloaderOperation cancel];
    }
    _photo = photo;
    
    if (self.photo.image) {
        self.imageView.image = self.photo.image;
        
    } else {

        _downloaderOperation = [[SDWebImageDownloader sharedDownloader] downloadImageWithURL:self.photo.URL options:SDWebImageDownloaderUseNSURLCache progress:^(NSInteger receivedSize, NSInteger expectedSize) {
            //
        } completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {
            
            dispatch_async(dispatch_get_main_queue(), ^(void) {
    
                if (error) {
                    [self handleFailedImage];
                    return ;
                }
                [self setupImageViewWithImage:image];
            });
      
        }];

    }
    
    if (self.imageView.image) {
        
        [_activityView stopAnimating];
        self.userInteractionEnabled = YES;
        _loading=NO;
        
    } else {
        _loading = YES;
        [_activityView startAnimating];
        self.userInteractionEnabled= NO;
        self.imageView.image = KPlaceholderImage;
    }
}

- (void)handleFailedImage{
    
    self.imageView.image = KPlaceholderImage;
    self.photo.failed = YES;
    
    self.userInteractionEnabled = NO;
    [_activityView stopAnimating];
    
}
- (void)setupImageViewWithImage:(UIImage*)aImage {
    if (!aImage) return;
    
    _loading = NO;
    [_activityView stopAnimating];
    self.imageView.image = aImage;
    
    [self.imageView.layer addAnimation:[self fadeAnimation] forKey:@"opacity"];
    self.userInteractionEnabled = YES;
}

#pragma mark - UIScrollView Delegate Methods
- (void)scrollViewDidZoom:(UIScrollView *)aScrollView
{
    CGFloat offsetX = (self.scrollView.bounds.size.width > self.scrollView.contentSize.width)?
    (self.scrollView.bounds.size.width - self.scrollView.contentSize.width) * 0.5 : 0.0;
    CGFloat offsetY = (self.scrollView.bounds.size.height > self.scrollView.contentSize.height)?
    (self.scrollView.bounds.size.height - self.scrollView.contentSize.height) * 0.5 : 0.0;
    self.imageView.center = CGPointMake(self.scrollView.contentSize.width * 0.5 + offsetX,
                                        self.scrollView.contentSize.height * 0.5 + offsetY);
    
}

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return self.imageView;
}

#pragma mark - Gesture Handers

- (void)singleTapHandle:(UITapGestureRecognizer *)gestureRecognizer
{
    if ([self.delegate respondsToSelector:@selector(photoViewDidSingleTap:)]) {
        [self.delegate photoViewDidSingleTap:self];
    }
}

-(void)handleDouble:(UITapGestureRecognizer *)gestureRecognizer
{
    float newScale = [self.scrollView zoomScale] * self.zoomStep;
    self.isScaleChanged = newScale > 1;
    CGPoint center = [gestureRecognizer locationInView:gestureRecognizer.view];
    [self resetImageViewScale:newScale Center:center];
}

- (void)resetImageViewScale:(float)scale Center:(CGPoint)center
{
    CGRect zoomRect = [self zoomRectForScale:scale withCenter:center];
    [self.scrollView zoomToRect:zoomRect animated:YES];
    self.zoomStep = 1/self.zoomStep;
}

- (CGRect)zoomRectForScale:(float)scale withCenter:(CGPoint)center {
    
    CGRect zoomRect;
    
    // the zoom rect is in the content view's coordinates.
    //    At a zoom scale of 1.0, it would be the size of the imageScrollView's bounds.
    //    As the zoom scale decreases, so more content is visible, the size of the rect grows.
    zoomRect.size.height = [self.scrollView frame].size.height / scale;
    zoomRect.size.width  = [self.scrollView  frame].size.width  / scale;
    
    // choose an origin so as to get the right center.
    zoomRect.origin.x    = center.x - (zoomRect.size.width  / 2.0);
    zoomRect.origin.y    = center.y - (zoomRect.size.height / 2.0);
    
    return zoomRect;
}

#pragma mark -
#pragma mark Animation

- (CABasicAnimation*)fadeAnimation{
    
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"opacity"];
    animation.fromValue = [NSNumber numberWithFloat:0.0f];
    animation.toValue = [NSNumber numberWithFloat:1.0f];
    animation.duration = .3f;
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
    
    return animation;
}
@end
